package com.lanhai.zhonglai.report;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import com.lanhai.zhonglai.beans.AgvBean;
import com.lanhai.zhonglai.beans.AgvDataBean;


/**
 * 记录每条指令时小车的状态（高频）
 *
 * @author zhengwei
 */
@EnableAsync
@Service
public class AgvStateMap {

    static Map<Integer, AgvStateBean> agvMap = new ConcurrentHashMap<Integer, AgvStateBean>();


    public void saveState(AgvDataBean bean, AgvBean agv) {
        try {
            AgvStateBean ab = new AgvStateBean();
            ab.setAgvid(bean.getAgvId());
            ab.setLastTime(System.currentTimeMillis());
            ab.setX(bean.getX());
            ab.setY(bean.getY());
            ab.setCmd(bean.getReceiveType().getName());
            ab.setNextNode(agv.getNexttStationName());
            ab.setSpecialline(agv.getSpecialline());
            ab.setProcess(agv.getNextProcess());

            ab.setUpHasTrans(agv.isUpHasTrans() ? 1 : 0);
            ab.setDownHasTrans(agv.isDownHasTrans() ? 1 : 0);
            ab.setFinishTrans(agv.isFinishTrans() ? 1 : 0);
            ab.setTransing(agv.isTransing() ? 1 : 0);

            agvMap.put(ab.getAgvid(), ab);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public synchronized List<AgvStateBean> getAll() {
        List<AgvStateBean> re = new ArrayList<AgvStateBean>();
        long t = System.currentTimeMillis() - 120000;  //2分钟前的时间

        for (Entry<Integer, AgvStateBean> entry : agvMap.entrySet()) {
            AgvStateBean mp = entry.getValue();
            if (mp.getLastTime() > t) {
                AgvStateBean ab = new AgvStateBean();
                ab.setAgvid(mp.getAgvid());
                ab.setLastTime(mp.getLastTime());
                ab.setX(mp.getX());
                ab.setY(mp.getY());
                ab.setCmd(mp.getCmd());
                ab.setNextNode(mp.getNextNode());
                ab.setSpecialline(mp.getSpecialline());
                ab.setProcess(mp.getProcess());
                ab.setFinishTrans(mp.getFinishTrans());
                ab.setUpHasTrans(mp.getUpHasTrans());
                ab.setDownHasTrans(mp.getDownHasTrans());
                ab.setTransing(mp.getTransing());
                re.add(ab);
            }
        }

        return re;
    }
}
